
import os
import time
import json
from flask import Flask, jsonify, request

from db_function import DataBaseFunction

app = Flask(__name__)

@app.route('/is_master_station', methods=['GET'])
def is_master_station():

    client_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

    if os.path.exists("base_station_ip.json"):

        with open("base_station_ip.json", encoding="utf-8") as f:

            '''{"192.168.31.22": 201923898, ... ...}'''

            base_station_info = json.loads(f.read())

            base_station_info[client_ip] = time.time() # 更新ip访问时间


    else:

        base_station_info = {client_ip: time.time()}


    count = 0

    for i in base_station_info.values(): # 迭代时间，判断时间是否过期

        if time.time() - i < 10 * 60:

            count += 1

    with open("/root/.base_station_ip_count", "w") as f:

        f.write(str(count))
        
        f.flush()

    with open("base_station_ip.json", "w") as f:

        f.write(json.dumps(base_station_info))

        f.flush()

    return jsonify(True)

@app.route('/ble_task', methods=['POST'])
def ble_task():

    ble_task = request.form.get("ble_task")

    try: 

        with DataBaseFunction() as df:

            df.insert_task(ble_task)

    except Exception as e:

        return {
            "status": -1,
            "errorCode": 100,
            "errorMsg": str(e),
            "resultBody": None,
        }

    else:

        return {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": {
                "type": "callback", 
                "data": {
                    "task_type": "callback", 
                    "task_id": ble_task["task_id"], 
                    "task_status": "receive", 
                    "notes": None, 
                    "result": None}

            }
        }


@app.route('/get_node_tree',)
def get_node_tree():

    base_station_mac = request.args.get("base_station_mac")

    if not base_station_mac:

        return  {
            "status": -1,
            "errorCode": 2000,
            "errorMsg": "参数不正确",
            "resultBody": None

        }

    with DataBaseFunction() as df:

        base_station_info = df.get_base_station_info_by_mac(base_station_mac)

        if not base_station_info:

            return  {
                "status": -1,
                "errorCode": 2001,
                "errorMsg": "请检查base_station_mac是否输入正确",
                "resultBody": None

            }


        brackets_info = df.get_brackets_info_by_base_station_id(base_station_info[0]["id"])

        sensors_info = []

        for bracket in brackets_info:

            info = df.get_sensors_info_by_brackets_id(bracket["id"])

            sensors_info.extend(info)

    result =  { 

        "base_station_info": base_station_info,
        "brackets_info": brackets_info,
        "sensors_info": sensors_info,
    }


    return {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": result

    }




if __name__ == '__main__':
    # 设置 IP 地址为 0.0.0.0，监听端口为 8080

    from util import get_network_info

    # get_network_info() # 放置self_host文件

    app.run(host='0.0.0.0', port=8080)